<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="新建病情资料"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      fixed
      placeholder
    />
    
    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 上次就诊信息 -->
      <view class="form-section">
        <view class="section-title">上次就诊信息</view>
        
        <!-- 上次就诊日期 -->
        <van-cell
          title="上次就诊日期"
          :value="formData.lastVisitDate"
          is-link
          @click="showDatePicker"
          required
        />
        
        <!-- 上次就诊医院 -->
        <van-cell
          title="上次就诊医院"
          :value="formData.lastVisitHospital"
          is-link
          @click="showHospitalPicker"
          required
        />
        
        <!-- 上次就诊结论 -->
        <van-field
          v-model="formData.lastVisitConclusion"
          label="上次就诊结论"
          type="textarea"
          placeholder="请填写上次就诊的结论或诊断结果"
          :rules="[{ required: true, message: '请填写就诊结论' }]"
          maxlength="200"
          show-word-limit
          required
        />
      </view>
      
      <!-- 当前病情描述 -->
      <view class="form-section">
        <view class="section-title">当前病情描述</view>
        
        <!-- 主要症状 -->
        <van-field
          v-model="formData.mainSymptoms"
          label="主要症状"
          type="textarea"
          placeholder="请填写患病时长、症状/异常、严重程度、持续时间,接受过的诊治、用药方案、治疗效果等"
          :rules="[{ required: true, message: '请填写主要症状' }]"
          maxlength="500"
          show-word-limit
          required
        />
        
        <!-- 当前病情症状 -->
        <view class="symptoms-section">
          <text class="symptoms-label">当前病情症状</text>
          <view class="symptoms-tags">
            <view 
              v-for="(symptom, index) in formData.symptoms" 
              :key="index"
              class="symptom-tag"
            >
              {{ symptom }}
              <van-icon 
                name="cross" 
                @click="removeSymptom(index)"
                class="remove-icon"
              />
            </view>
            <view class="add-symptom-btn" @click="showSymptomInput">
              <van-icon name="plus" />
            </view>
          </view>
        </view>
      </view>
      
      <!-- 辅助检查 -->
      <view class="form-section">
        <view class="section-title">辅助检查 (选填)</view>
        <view class="upload-section">
          <text class="upload-tip">请上传病情相关照片,如,病历、检查单、患处照片、先服药品、出院证明等</text>
          <view class="upload-area" @click="uploadImage">
            <van-icon name="plus" size="40" color="#ccc" />
            <text class="upload-text">上传图片</text>
          </view>
          <text class="upload-count">{{ uploadedImages.length }}/10</text>
        </view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-action">
      <van-button 
        type="default" 
        size="large"
        @click="goBack"
        class="prev-btn"
      >
        上一步
      </van-button>
      <van-button 
        type="primary" 
        size="large"
        @click="completeAndPay"
        class="complete-btn"
      >
        完成并支付
      </van-button>
    </view>
    
    <!-- 日期选择器 -->
    <van-popup v-model:show="showDate" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        @confirm="onDateConfirm"
        @cancel="showDate = false"
      />
    </van-popup>
    
    <!-- 医院选择器 -->
    <van-popup v-model:show="showHospital" position="bottom">
      <van-picker
        :columns="hospitalOptions"
        @confirm="onHospitalConfirm"
        @cancel="showHospital = false"
      />
    </van-popup>
    
    <!-- 症状输入弹窗 -->
    <van-popup v-model:show="showSymptomPopup" position="bottom">
      <view class="symptom-input-popup">
        <view class="popup-header">
          <text class="popup-title">添加症状</text>
          <van-icon name="cross" @click="showSymptomPopup = false" />
        </view>
        <van-field
          v-model="newSymptom"
          placeholder="请输入症状描述"
          @confirm="addSymptom"
        />
        <van-button type="primary" @click="addSymptom" block>确定</van-button>
      </view>
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

// 表单数据接口
interface FormData {
  lastVisitDate: string
  lastVisitHospital: string
  lastVisitConclusion: string
  mainSymptoms: string
  symptoms: string[]
}

// 响应式数据
const formData = ref<FormData>({
  lastVisitDate: '',
  lastVisitHospital: '',
  lastVisitConclusion: '',
  mainSymptoms: '',
  symptoms: []
})

const showDate = ref(false)
const showHospital = ref(false)
const showSymptomPopup = ref(false)
const currentDate = ref(new Date())
const newSymptom = ref('')
const uploadedImages = ref<string[]>([])

// 页面参数
const doctorId = ref('')
const doctorName = ref('')
const departmentName = ref('')
const consultationPrice = ref(0)
const cardId = ref('')
const cardName = ref('')
const recordId = ref('')

// 医院选项
const hospitalOptions = [
  '华西',
  '四川省人民医院',
  '成都市第一人民医院',
  '成都市第二人民医院',
  '成都市第三人民医院'
]

// 显示日期选择器
const showDatePicker = () => {
  showDate.value = true
}

// 确认日期选择
const onDateConfirm = (value: Date) => {
  formData.value.lastVisitDate = formatDate(value)
  showDate.value = false
}

// 显示医院选择器
const showHospitalPicker = () => {
  showHospital.value = true
}

// 确认医院选择
const onHospitalConfirm = (value: string) => {
  formData.value.lastVisitHospital = value
  showHospital.value = false
}

// 显示症状输入弹窗
const showSymptomInput = () => {
  showSymptomPopup.value = true
}

// 添加症状
const addSymptom = () => {
  if (newSymptom.value.trim()) {
    formData.value.symptoms.push(newSymptom.value.trim())
    newSymptom.value = ''
    showSymptomPopup.value = false
  }
}

// 移除症状
const removeSymptom = (index: number) => {
  formData.value.symptoms.splice(index, 1)
}

// 上传图片
const uploadImage = () => {
  if (uploadedImages.value.length >= 10) {
    uni.showToast({
      title: '最多上传10张图片',
      icon: 'none'
    })
    return
  }
  
  // 模拟上传
  uni.chooseImage({
    count: 1,
    success: (res) => {
      uploadedImages.value.push(res.tempFilePaths[0])
    }
  })
}

// 完成并支付
const completeAndPay = () => {
  // 验证表单
  if (!formData.value.lastVisitDate) {
    uni.showToast({
      title: '请选择上次就诊日期',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.lastVisitHospital) {
    uni.showToast({
      title: '请选择上次就诊医院',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.lastVisitConclusion.trim()) {
    uni.showToast({
      title: '请填写就诊结论',
      icon: 'none'
    })
    return
  }
  
  if (!formData.value.mainSymptoms.trim()) {
    uni.showToast({
      title: '请填写主要症状',
      icon: 'none'
    })
    return
  }
  
  console.log('完成病情资料填写:', formData.value)
  
  // 保存病情资料
  saveMedicalRecord()
  
  // 跳转到收银台页面
  const url = `/pages/online-consultation/cashier?doctorId=${doctorId.value}&doctorName=${doctorName.value}&departmentName=${departmentName.value}&consultationPrice=${consultationPrice.value}&cardId=${cardId.value}&cardName=${cardName.value}`
  console.log('跳转收银台URL:', url)
  
  uni.navigateTo({
    url: url
  })
}

// 保存病情资料
const saveMedicalRecord = () => {
  const medicalRecord = {
    id: Date.now(),
    patientName: cardName.value,
    gender: '男', // 这里可以从就诊卡信息获取
    age: 25, // 这里可以从就诊卡信息获取
    condition: formData.value.mainSymptoms,
    department: departmentName.value,
    doctor: doctorName.value,
    consultationType: '线上门诊',
    consultationDate: new Date().toISOString().split('T')[0],
    lastVisitDate: formData.value.lastVisitDate,
    lastVisitHospital: formData.value.lastVisitHospital,
    lastVisitConclusion: formData.value.lastVisitConclusion,
    mainSymptoms: formData.value.mainSymptoms,
    symptoms: formData.value.symptoms,
    images: uploadedImages.value,
    createTime: new Date().toISOString()
  }
  
  // 保存到本地存储
  const existingRecords = uni.getStorageSync('medicalRecords') || '[]'
  const records = JSON.parse(existingRecords)
  records.push(medicalRecord)
  uni.setStorageSync('medicalRecords', JSON.stringify(records))
  
  console.log('病情资料保存成功:', medicalRecord)
}

// 格式化日期
const formatDate = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面加载
onLoad((options: Record<string, string>) => {
  console.log('新建病情资料页面 onLoad', options)
  
  doctorId.value = options.doctorId || ''
  doctorName.value = options.doctorName || ''
  departmentName.value = options.departmentName || ''
  consultationPrice.value = parseFloat(options.consultationPrice || '0')
  cardId.value = options.cardId || ''
  cardName.value = options.cardName || ''
  recordId.value = options.recordId || ''
  
  console.log('接收到的参数:', {
    doctorId: doctorId.value,
    doctorName: doctorName.value,
    departmentName: departmentName.value,
    consultationPrice: consultationPrice.value,
    cardId: cardId.value,
    cardName: cardName.value,
    recordId: recordId.value
  })
  
  // 如果有现有病情资料，加载数据
  if (recordId.value) {
    loadExistingRecord()
  }
  
  // 设置默认值
  formData.value.lastVisitDate = new Date().toISOString().split('T')[0]
  formData.value.lastVisitHospital = '华西'
})

// 加载现有病情资料
const loadExistingRecord = () => {
  const existingRecords = uni.getStorageSync('medicalRecords') || '[]'
  const records = JSON.parse(existingRecords)
  const record = records.find((r: any) => r.id.toString() === recordId.value)
  
  if (record) {
    formData.value.lastVisitDate = record.lastVisitDate || ''
    formData.value.lastVisitHospital = record.lastVisitHospital || ''
    formData.value.lastVisitConclusion = record.lastVisitConclusion || ''
    formData.value.mainSymptoms = record.mainSymptoms || ''
    formData.value.symptoms = record.symptoms || []
    uploadedImages.value = record.images || []
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.main-content {
  padding: 20rpx;
}

.form-section {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 30rpx;
}

.symptoms-section {
  margin-top: 20rpx;
}

.symptoms-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.symptoms-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.symptom-tag {
  background: #07c160;
  color: white;
  padding: 16rpx 24rpx;
  border-radius: 20rpx;
  font-size: 26rpx;
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.remove-icon {
  font-size: 20rpx;
}

.add-symptom-btn {
  border: 2rpx dashed #ccc;
  border-radius: 20rpx;
  padding: 16rpx 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ccc;
  font-size: 26rpx;
}

.upload-section {
  margin-top: 20rpx;
}

.upload-tip {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 20rpx;
  display: block;
}

.upload-area {
  border: 2rpx dashed #ccc;
  border-radius: 16rpx;
  padding: 60rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.upload-text {
  font-size: 26rpx;
  color: #999;
}

.upload-count {
  font-size: 24rpx;
  color: #999;
  text-align: right;
}

.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background: white;
  border-top: 1rpx solid #f0f0f0;
}

.prev-btn {
  flex: 1;
  border: 2rpx solid #07c160;
  color: #07c160;
  border-radius: 25rpx;
  height: 88rpx;
  font-size: 32rpx;
}

.complete-btn {
  flex: 1;
  background: #07c160;
  border: none;
  border-radius: 25rpx;
  height: 88rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.symptom-input-popup {
  background: white;
  padding: 40rpx;
  border-radius: 20rpx 20rpx 0 0;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}
</style>
